using System;
using System.Collections.Generic;
using System.Text;
using Jbe.TestSuite.Help.Interface.Services;
using Microsoft.Practices.CompositeUI;
using System.IO;
using System.Reflection;
using Microsoft.Practices.CompositeUI.EventBroker;
using Jbe.TestSuite.Help.Constants;
using Microsoft.Practices.CompositeUI.Utility;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Jbe.TestSuite.Help.Services
{
    public class DynamicHelpService : IDynamicHelp
    {
        [EventPublication(EventTopicNames.HelpUriUpdate, PublicationScope.Global)]
        public event EventHandler<DataEventArgs<Uri>> HelpUriUpdate;

        private WorkItem workItem;

        [ServiceDependency]
        public WorkItem WorkItem
        {
            set { workItem = value; }
        }

        public void ShowHelp(Assembly executingAssembly, string helpUrl)
        {
            Uri url = TryCreateUri(helpUrl);
            
            if (url == null)
            {
                helpUrl = "file://" + Path.GetDirectoryName(executingAssembly.Location) + "/" + helpUrl;
                url = TryCreateUri(helpUrl);
            }

            if (url == null)
            {
                throw new ArgumentException("helpUrl is invalid");
            }

            Log("ShowHelp Uri: " + url.ToString());
            OnHelpUriUpdate(new DataEventArgs<Uri>(url));    
        }

        protected virtual void OnHelpUriUpdate(DataEventArgs<Uri> eventArgs)
        {
            if (HelpUriUpdate != null)
            {
                HelpUriUpdate(this, eventArgs);
            }
        }

        private static Uri TryCreateUri(string url)
        {
            Uri uri = null;
            try
            {
                uri = new Uri(url); ;
            }
            catch (UriFormatException) { }

            return uri;
        }

        private static void Log(string message)
        {
            LogEntry entry = new LogEntry();
            entry.Message = message;
            entry.Title = "DynamicHelpService";
            entry.Categories.Add("Help");
            Logger.Write(entry);
        }
    }
}
